from sqlalchemy import and_, or_, func, text
from datetime import datetime, timedelta
from app import db
from app.models.user import User
from app.models.user_profile import UserProfile
from app.models.user_photo import UserPhoto
from app.models.mate_criteria import MateCriteria


class AdminUserService:
    """后台用户管理服务层"""
    
    @staticmethod
    def get_user_list(page=1, per_page=20, filters=None):
        """
        获取用户列表（后台管理）
        
        Args:
            page: 页码
            per_page: 每页数量
            filters: 筛选条件
            
        Returns:
            dict: 分页用户数据
        """
        if filters is None:
            filters = {}
        
        query = User.query
        
        # 关键词搜索
        keyword = filters.get('keyword', '').strip()
        if keyword:
            query = query.filter(or_(
                User.nickname.like(f'%{keyword}%'),
                User.real_name.like(f'%{keyword}%'),
                User.phone.like(f'%{keyword}%'),
                User.openid.like(f'%{keyword}%')
            ))
        
        # 状态筛选
        status = filters.get('status')
        if status is not None:
            query = query.filter(User.status == status)
        
        # 性别筛选
        gender = filters.get('gender')
        if gender is not None:
            query = query.filter(User.gender == gender)
        
        # 年龄筛选
        min_age = filters.get('min_age')
        max_age = filters.get('max_age')
        if min_age is not None:
            query = query.filter(User.age >= min_age)
        if max_age is not None:
            query = query.filter(User.age <= max_age)
        
        # 城市筛选
        city = filters.get('city', '').strip()
        if city:
            query = query.filter(or_(
                User.city.like(f'%{city}%'),
                User.province.like(f'%{city}%')
            ))
        
        # VIP等级筛选
        vip_level = filters.get('vip_level')
        if vip_level is not None:
            query = query.filter(User.vip_level == vip_level)
        
        # 注册时间筛选
        start_date = filters.get('start_date', '').strip()
        end_date = filters.get('end_date', '').strip()
        if start_date:
            try:
                start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
                query = query.filter(User.created_at >= start_datetime)
            except ValueError:
                pass
        if end_date:
            try:
                end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
                query = query.filter(User.created_at < end_datetime)
            except ValueError:
                pass
        
        # 按注册时间倒序
        query = query.order_by(User.created_at.desc())
        
        # 获取总数
        total = query.count()
        
        # 分页查询
        users = query.offset((page - 1) * per_page).limit(per_page).all()
        
        # 格式化用户数据
        user_list = []
        for user in users:
            user_data = user.to_dict()
            
            # 添加额外信息
            user_data['photo_count'] = UserPhoto.query.filter_by(user_id=user.id).count()
            user_data['has_profile'] = user.profile is not None
            user_data['has_mate_criteria'] = MateCriteria.query.filter_by(user_id=user.id).first() is not None
            user_data['completeness'] = user.get_profile_completeness()
            
            user_list.append(user_data)
        
        return {
            'users': user_list,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': total,
                'total_pages': (total + per_page - 1) // per_page
            }
        }
    
    @staticmethod
    def get_user_detail(user_id):
        """
        获取用户详细信息
        
        Args:
            user_id: 用户ID
            
        Returns:
            dict: 用户详细信息
        """
        user = User.query.get(user_id)
        if not user:
            return None
        
        # 基础信息
        user_data = user.to_dict()
        
        # 详细资料
        if user.profile:
            user_data['profile'] = user.profile.to_dict()
        
        # 照片信息
        photos = UserPhoto.query.filter_by(user_id=user_id).order_by(UserPhoto.sort_order.asc()).all()
        user_data['photos'] = [photo.to_dict() for photo in photos]
        
        # 择偶条件
        mate_criteria = MateCriteria.query.filter_by(user_id=user_id).first()
        if mate_criteria:
            user_data['mate_criteria'] = mate_criteria.to_dict()
        
        # 统计信息
        user_data['completeness'] = user.get_profile_completeness()
        user_data['photo_count'] = len(photos)
        user_data['login_info'] = {
            'login_count': user.login_count or 0,
            'last_login_time': user.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if user.last_login_time else None
        }
        
        return user_data
    
    @staticmethod
    def update_user_status(user_id, status, admin_id=None):
        """
        更新用户状态
        
        Args:
            user_id: 用户ID
            status: 新状态
            admin_id: 操作管理员ID
            
        Returns:
            dict: 更新后的用户信息
        """
        user = User.query.get(user_id)
        if not user:
            return None
        
        old_status = user.status
        user.status = status
        user.updated_at = datetime.now()
        
        db.session.commit()
        
        # 记录操作日志（可以后续扩展）
        # AdminOperationLog.create_log(admin_id, 'update_user_status', f'用户{user_id}状态从{old_status}改为{status}')
        
        return user.to_dict()
    
    @staticmethod
    def delete_user(user_id, admin_id=None):
        """
        删除用户（软删除）
        
        Args:
            user_id: 用户ID
            admin_id: 操作管理员ID
            
        Returns:
            bool: 是否删除成功
        """
        user = User.query.get(user_id)
        if not user:
            return False
        
        # 软删除：设置状态为注销
        user.status = 5  # 注销状态
        user.updated_at = datetime.now()
        
        db.session.commit()
        
        # 记录操作日志
        # AdminOperationLog.create_log(admin_id, 'delete_user', f'删除用户{user_id}')
        
        return True
    
    @staticmethod
    def get_user_statistics():
        """
        获取用户统计数据
        
        Returns:
            dict: 统计数据
        """
        # 总用户数
        total_users = User.query.count()
        
        # 各状态用户数
        status_stats = {}
        for status in [1, 2, 3, 4, 5]:
            status_stats[f'status_{status}'] = User.query.filter(User.status == status).count()
        
        # 性别统计
        male_count = User.query.filter(User.gender == 1).count()
        female_count = User.query.filter(User.gender == 2).count()
        
        # VIP用户统计
        vip_stats = {}
        for level in [0, 1, 2, 3]:
            vip_stats[f'vip_{level}'] = User.query.filter(User.vip_level == level).count()
        
        # 今日统计
        today = datetime.now().date()
        today_new = User.query.filter(func.date(User.created_at) == today).count()
        today_active = User.query.filter(func.date(User.last_login_time) == today).count()
        
        # 本周统计
        week_ago = datetime.now() - timedelta(days=7)
        week_new = User.query.filter(User.created_at >= week_ago).count()
        
        # 本月统计
        month_start = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        month_new = User.query.filter(User.created_at >= month_start).count()
        
        # 年龄分布
        age_stats = {
            'age_18_25': User.query.filter(and_(User.age >= 18, User.age <= 25)).count(),
            'age_26_30': User.query.filter(and_(User.age >= 26, User.age <= 30)).count(),
            'age_31_35': User.query.filter(and_(User.age >= 31, User.age <= 35)).count(),
            'age_36_40': User.query.filter(and_(User.age >= 36, User.age <= 40)).count(),
            'age_40_plus': User.query.filter(User.age > 40).count()
        }
        
        # 资料完整度统计
        users_with_profile = User.query.join(UserProfile).count()
        users_with_photos = User.query.join(UserPhoto).distinct().count()
        users_with_criteria = User.query.join(MateCriteria).count()
        
        return {
            'total_users': total_users,
            'status_stats': status_stats,
            'gender_stats': {
                'male': male_count,
                'female': female_count
            },
            'vip_stats': vip_stats,
            'time_stats': {
                'today_new': today_new,
                'today_active': today_active,
                'week_new': week_new,
                'month_new': month_new
            },
            'age_stats': age_stats,
            'profile_stats': {
                'has_profile': users_with_profile,
                'has_photos': users_with_photos,
                'has_mate_criteria': users_with_criteria,
                'profile_rate': round((users_with_profile / max(total_users, 1)) * 100, 2),
                'photo_rate': round((users_with_photos / max(total_users, 1)) * 100, 2)
            }
        }
    
    @staticmethod
    def export_users(filters=None):
        """
        导出用户数据
        
        Args:
            filters: 筛选条件
            
        Returns:
            dict: 导出数据
        """
        if filters is None:
            filters = {}
        
        # 构建查询（复用get_user_list的逻辑，但不分页）
        query = User.query
        
        # 应用筛选条件（省略重复代码，实际实现时复制筛选逻辑）
        # ... 筛选逻辑 ...
        
        users = query.order_by(User.created_at.desc()).all()
        
        # 格式化导出数据
        export_data = []
        for user in users:
            row = {
                'ID': user.id,
                '昵称': user.nickname,
                '真实姓名': user.real_name,
                '性别': user.get_gender_text(),
                '年龄': user.age,
                '手机号': user.phone or '',
                '城市': f"{user.province or ''} {user.city or ''}".strip(),
                '状态': user.get_status_text(),
                'VIP等级': user.get_vip_level_text(),
                '注册时间': user.created_at.strftime('%Y-%m-%d %H:%M:%S') if user.created_at else '',
                '最后登录': user.last_login_time.strftime('%Y-%m-%d %H:%M:%S') if user.last_login_time else '',
                '登录次数': user.login_count or 0
            }
            export_data.append(row)
        
        return {
            'data': export_data,
            'count': len(export_data),
            'export_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        } 